/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.inter.authc.realm;

import cn.simastudio.talos.core.authc.realm.AbstractOAuth2Realm;
import cn.simastudio.talos.core.authc.token.OAuth2Token;
import cn.simastudio.talos.core.authc.utils.SimaByteSource;
import cn.simastudio.talos.inter.model.inst.Member;
import cn.simastudio.talos.inter.service.inst.MemberService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 14-2-18
 * <p>Version: 1.0
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
public class OAuth2Realm extends AbstractOAuth2Realm {

    @Autowired
    private MemberService memberService;

    @Override
    public boolean supports(AuthenticationToken token) {
        // 表示此Realm只支持OAuth2Token类型
        return token instanceof OAuth2Token;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();

        //暂时不加权限
        return new SimpleAuthorizationInfo();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String credential = (String) token.getPrincipal();

        // 这边进行登录具体操作，参见cn.simastudio.talos.common.system.authc.realm.SimaRealm.doGetAuthenticationInfo()
        Member member = memberService.findByMemberNameForAuth(credential);

        if (member == null) {
            throw new UnknownAccountException();//没找到帐号
        }

        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        return new SimpleAuthenticationInfo(
                member.getUsername(), //用户名
                member.getPassword(), //密码
                // Sima: 注意这边CredentialsSalt的设置需要和生成密码加密的方式相对应，即密码如果是用户名和密码和加密盐去hash的，这边就要取用户名和加密盐来hash
                new SimaByteSource(member.getCredentialsSalt()),
                getName()  //realm name
        );
    }
}
